package handler

import (
	"log"
	"math/rand"
	"net/http"
	"os"
	"time"
	"webserver/metrics"
)

func DefaultHandler(w http.ResponseWriter, r *http.Request) {
	log.Println("Client IP:", r.RemoteAddr)
	timer := metrics.NewTimer()
	defer timer.ObserveTotal()
	//随机休眠
	duration := sleepTime(0, 2000)
	log.Println("Sleep time(ms):", duration)
	time.Sleep(time.Duration(duration) * time.Millisecond)

	reqHeader := r.Header
	respHeader := w.Header()
	for k, v := range reqHeader {
		for _, strVal := range v {
			respHeader.Add(k, strVal)
		}
	}

	version := os.Getenv("VERSION")
	respHeader.Add("version", version)

	w.Write([]byte("Hello Go!"))

	return
}

func sleepTime(min int, max int) int {
	rand.Seed(time.Now().UnixNano())
	return min + rand.Intn(max)
}
